<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :class="{disable: fileList.length>0}"
      :on-remove="onRemove"
      :http-request="httpRequest"
      :on-change="onChange"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress
      v-if="isShowProgress"
      :text-inside="true"
      :stroke-width="26"
      :percentage="defultProcess"
    />
  </div>
</template>

<script>
var COS = require('cos-js-sdk-v5')
var cos = new COS({
  SecretId: 'AKIDOYS6TZOxEExPbV8UcU6RWKr76oFPHtEI',
  SecretKey: 'oNfbGeroUt1waw2rPfeNp1wbz5uTlmVz'
})
export default {
  data() {
    return {
      fileList: [],
      defultProcess: 0,
      isShowProgress: false
    }
  },
  methods: {
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    // 上传前的校验
    beforeUpload(file) {
      const maxSize = 5 * 1024 * 1024
      const whiteList = ['image/jpeg', 'image/png']
      if (file.size > maxSize) {
        this.$message.warning('上传图片不能超过5M哦')
        return false
      } else if (!whiteList.includes(file.type)) {
        this.$message.warning('暂时只支持 jpeg / png 格式图片')
        return false
      }
    },
    httpRequest(params) {
      // 覆盖默认的上传行为，可以自定义上传的实现
      this.isShowProgress = true
      cos.putObject({
        Bucket: 'renzi-1-1304735612', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          this.defultProcess = progressData.percent * 100
        }
      }, (err, data) => {
        if (!err) {
          this.fileList[0].status = 'success'
          this.fileList[0].url = 'https://' + data.Location
        }
        setTimeout(() => {
          this.isShowProgress = false
        }, 500)
      })
    },
    onChange(file, fileList) {
      this.fileList = fileList
    }
  }
}
</script>

<style lang="scss" scoped>
    .disable {
    ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
